// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
export interface StockData {
  name: string;
  currentPrice: string;
  // lastClosePrice: string;
  profitLoss: string;
}

export function parseStockData(rawData: string): StockData | null {
  // 正则表达式匹配股票名称、当前价和昨收盘价
  const value = rawData.split("=");
  if (value.length < 2) {
    return null;
  }
  const d = value[1].split("~");
  if (d.length < 3) {
    return null;
  }

  // 计算涨跌额和涨跌幅度
  const currentPriceNum = parseFloat(d[1]);
  const lastClosePriceNum = parseFloat(d[2]);
  const profitLossValue = currentPriceNum - lastClosePriceNum;
  const profitLossPercentage =
    (Math.abs(profitLossValue) / lastClosePriceNum) * 100;

  // 根据涨跌额的正负确定涨跌符号
  let profitLossSign = "";
  let padding = "";
  if (profitLossValue >= 0) {
    profitLossSign = "";
    padding = "";
  } else if (profitLossValue < 0) {
    padding = "";
    profitLossSign = "-";
  }
  // if (profitLossValue >= 0) {
  //   profitLossSign = "+";
  // } else if (profitLossValue < 0) {
  //   profitLossSign = "-";
  // }
  // 格式化涨跌额和涨跌幅度为字符串↑ ↓
  const profitLoss = `${profitLossSign}${profitLossPercentage.toFixed(
    2
  )}%${padding}`;
  return {
    name: d[0].replace('"', ""),
    currentPrice: d[1],
    // lastClosePrice: d[2],
    profitLoss,
  };
}

// 解析整个字符串，返回所有股票数据的数组
export function parseStockDataList(rawData: string): StockData[] {
  // 将整个字符串分割成单个股票数据
  const stockDataStrings = rawData.split(";");
  // 过滤掉空字符串，并解析每个股票数据
  return stockDataStrings
    .filter((str) => str)
    .map((str) => parseStockData(str))
    .filter((data) => data !== null) as StockData[]; // 移除null项
}
